package cn.itcast.erp.resolver;


import cn.itcast.erp.exception.SameUsernameException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        ModelAndView mv = new ModelAndView ( );

        if(ex instanceof SameUsernameException) {
            mv.addObject ("message", "用户名已存在");
            mv.setView (new MappingJackson2JsonView ( ));
//        }else {
//            //打印异常的堆栈信息(没处理的异常打印出来)
//            ex.printStackTrace ();
//            mv.addObject ("message","服务器开小差了");
//            mv.setView (new MappingJackson2JsonView ());
        } else {
            //打印异常的堆栈信息(没处理的异常打印出来)
            ex.printStackTrace ();
            mv.addObject ("message","服务器开小差了");
            mv.setView (new MappingJackson2JsonView ());
        }
        return mv;
    }
}
